<?php

class Sfs_Csv implements Iterator
{
    const ROW_SIZE = 4096;

    private $filePointer;
    private $currentElement;
    private $rowCounter;
    private $delimiter;

    /**
     * 對CSV 進行處理
     * @param resource handle
     * @param int length
     * @param string delimiter
     * @param string enclosure
     * @return 文件内容或FALSE。
     */
    private function __fgetcsv(& $handle, $length = null, $d = ',', $e = '"') {
        $d = preg_quote($d);
        $e = preg_quote($e);
        $_line = "";
        $eof=false;
        while ($eof != true) {
            $_line .= (empty ($length) ? fgets($handle) : fgets($handle, $length));
            $itemcnt = preg_match_all('/' . $e . '/', $_line, $dummy);
            if ($itemcnt % 2 == 0)
            $eof = true;
        }
        $_csv_line = preg_replace('/(?: |[ ])?$/', $d, trim($_line));
        $_csv_pattern = '/(' . $e . '[^' . $e . ']*(?:' . $e . $e . '[^' . $e . ']*)*' . $e . '|[^' . $d . ']*)' . $d . '/';
        preg_match_all($_csv_pattern, $_csv_line, $_csv_matches);
        $_csv_data = $_csv_matches[1];
        for ($_csv_i = 0; $_csv_i < count($_csv_data); $_csv_i++) {
            $_csv_data[$_csv_i] = preg_replace('/^' . $e . '(.*)' . $e . '$/s','$1', $_csv_data[$_csv_i]);
            $_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);
        }
        return empty ($_line) ? false : $_csv_data;
    }


    public function __construct( $file, $delimiter = ',' )
    {
        $this->filePointer = fopen( $file, 'r' );
        $this->delimiter   = $delimiter;
    }

    public function rewind()
    {
        $this->rowCounter = 0;
        rewind( $this->filePointer );
    }

    public function current()
    {
        $this->currentElement = $this->__fgetcsv( $this->filePointer, self::ROW_SIZE, $this->delimiter );
        $this->rowCounter++;
        return $this->currentElement;
    }

    public function key()
    {
        return $this->rowCounter;
    }

    public function next()
    {
        return !feof( $this->filePointer );
    }

    public function valid()
    {
        if( !$this->next() )
        {
            fclose( $this->filePointer );
            return FALSE;
        }
        return TRUE;
    }

} // end class
